<?php
include $_SERVER['DOCUMENT_ROOT']."/server/util/spyc.php";

/**
 * 数据库操作类
 */
class DB
{
    private $DBenv;
    private $mysqli;
    private $stmt;

    public function __construct()
    {
        $this->DBenv = spyc_load_file($_SERVER['DOCUMENT_ROOT'].'/server/properties/env.yml');
        // 连接MySQL数据库
        mysqli_report(MYSQLI_REPORT_ERROR); // 报告所有的MySQL错误
        $this->mysqli = new mysqli(($this->DBenv['db']['host'])['0'], ($this->DBenv['db']['username'])['0'], ($this->DBenv['db']['password'])['0'], ($this->DBenv['db']['database'])['0']);
        if (!$this->mysqli) {
            die("无法连接到数据库...\n" . mysqli_connect_error());
        }
    }

    /**
     * 执行查询语句，返回执行结果
     * @param  [string] $sql          [SQL语句]
     * @param  [string] $paramTypeStr [参数类型字符串]
     * @param  [array] $params        [参数数组]
     * @param  [array] $result        [结果变量数组]
     * @return [array]          [查询结果集]
     */
    public function select($sql, $paramTypeStr, $params)
    {
        $this->stmt = $this->mysqli->prepare($sql);
        if ($this->stmt) {
            $this->stmt->bind_param($paramTypeStr, ...$params);
            $result = $this->stmt->execute();
            if (!$result) {
                return null; // 查询出错
            }
            $result =  $this->stmt->get_result();
            $this->stmt->close();
            return $result->fetch_all(MYSQLI_ASSOC);
        } else {
            echo "select()=>SQL语句编译出错";
            return null; // SQL语句编译出错
        }
    }

    /**
     * 执行更新语句，返回执行结果
     * @param  [string] $sql          [SQL语句]
     * @param  [string] $paramTypeStr [参数类型]
     * @param  [array] $params       [参数数组]
     * @return [bool]               [SQL执行结果]
     */
    public function update($sql, $paramTypeStr, $params)
    {
        $this->stmt = $this->mysqli->prepare($sql);
        if ($this->stmt) {
            $this->stmt->bind_param($paramTypeStr, ...$params);
            $result = $this->stmt->execute();
            $this->stmt->close();
            return $result;
        } else {
            echo "update()=>SQL语句编译出错";
            return false; // SQL语句编译出错
        }
    }

    /**
     * 关闭数据库连接
     * @return [type] [description]
     */
    public function close()
    {
        if ($this->tmt) {
            $this->stmt->close();
        }
        if ($this->mysqli) {
            $this->mysqli->close();
        }
    }
}
